//
//  NSString+MD5.m
//  JiuXiao
//
//  Created by wp_g4 on 12-5-16.
//  Copyright (c) 2012年 gameu. All rights reserved.
//

#import "NSString+MD5.h"
#import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access

@implementation NSString (MD5)

- (NSString *)md5
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result ); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

@end

@implementation NSString (compress)

/** 压缩字符串到指定字节数
 *
 *
 *
 */
- (NSString *)compressStringToLimitedDataLength:(NSUInteger)limitedLegnth
{

    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];

    NSUInteger i = 1;

    while ( dataLength > limitedLegnth)
    {
        if ( self.length <= i )
        {
            data = [self dataUsingEncoding:NSUTF8StringEncoding];
            break;
        }
        //每次减少一个字符
        NSString *subString = [self substringToIndex:self.length - i];
        data = [subString dataUsingEncoding:NSUTF8StringEncoding];
        dataLength = [data length];

        i++;
    }

    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

}

@end
